/*
 * Copyright 2021 TiKV Project Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.webank.tikv.util;

import com.google.common.base.Preconditions;
import com.webank.tikv.exception.TiKVException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.webank.tikv.util.BackOffer.BoType.BoCheckTimeout;
import static com.webank.tikv.util.BackOffer.Strategy.EqualJitter;
import static com.webank.tikv.util.BackOffer.Strategy.NoJitter;

@SuppressWarnings("DuplicateBranchesInSwitch")
public class ConcreteBackOffer implements BackOffer {

    private static final Logger LOGGER = LogManager.getLogger(ConcreteBackOffer.class);

    // 缓存无状态的BackOfferFunction对象, 避免重创建
    private static final Map<BoType, BackOfferFunction> backOffFuncMap = new ConcurrentHashMap<>();

    private final int maxSleep;
    private final long deadline;
    private long totalSleep;
    private long lastSleep;
    private int attempts;

    private ConcreteBackOffer(int maxSleep, long deadline) {
        Preconditions.checkArgument(maxSleep == 0 || deadline == 0,
            "Max sleep should be 0 or Deadline should be 0");
        Preconditions.checkArgument(maxSleep >= 0, "Max sleep cannot be less than 0");
        Preconditions.checkArgument(deadline >= 0, "Deadline cannot be less than 0");
        this.maxSleep = maxSleep;
        this.deadline = deadline;
    }

    public static ConcreteBackOffer newDeadlineBackOff(int timeoutInMs) {
        long deadline = System.currentTimeMillis() + timeoutInMs;
        return new ConcreteBackOffer(0, deadline);
    }

    public static ConcreteBackOffer newCustomBackOff(int maxSleep) {
        return new ConcreteBackOffer(maxSleep, 0);
    }

    /**
     * Creates a back off func which implements exponential back off with optional jitters according
     * to different back off strategies. See <a href="http://www.awsarchitectureblog.com/2015/03/backoff.html">...</a>
     */
    private BackOfferFunction createBackOffFunc(BoType type) {
        BackOfferFunction backOfferFunction;
        switch (type) {
            case BoTiKVRPC:
                backOfferFunction = BackOfferFunction.create(100, 2000, EqualJitter);
                break;
            case BoPDRPC:
                backOfferFunction = BackOfferFunction.create(500, 3000, EqualJitter);
                break;
            case BoRegionMiss:
            case BoRegionScheduling:
                backOfferFunction = BackOfferFunction.create(2, 2000, NoJitter);
                break;
            case BoRegionRecoveryInProgress:
                backOfferFunction = BackOfferFunction.create(100, 10000, EqualJitter);
                break;
            case BoMaxRegionNotInitialized:
                backOfferFunction = BackOfferFunction.create(2, 1000, NoJitter);
                break;
            case BoUpdateLeader:
                backOfferFunction = BackOfferFunction.create(1, 2000, NoJitter);
                break;
            case BoServerBusy:
                backOfferFunction = BackOfferFunction.create(2000, 10000, EqualJitter);
                break;
            case BoDiskFull:
                backOfferFunction = BackOfferFunction.create(500, 5000, NoJitter);
                break;
            case BoTsoBatchUsedUp:
                backOfferFunction = BackOfferFunction.create(20, 500, NoJitter);
                break;
            case BoMaxTsNotSynced:
                backOfferFunction = BackOfferFunction.create(2, 500, NoJitter);
                break;
            case BoCheckHealth:
                backOfferFunction = BackOfferFunction.create(100, 600, EqualJitter);
                break;
            case BoIsWitness:
                backOfferFunction = BackOfferFunction.create(1000, 10000, NoJitter);
                break;
            case BoStaleCmd:
                backOfferFunction = BackOfferFunction.create(5, 1000, NoJitter);
                break;
            case BoCheckTimeout:
                backOfferFunction = BackOfferFunction.create(0, 0, NoJitter);
                break;
            // txn
            case BoTxnNotFound:
                backOfferFunction = BackOfferFunction.create(2, 500, NoJitter);
                break;
            case BoTxnLock:
                backOfferFunction = BackOfferFunction.create(100, 3000, EqualJitter);
                break;
            case BoTxnLockFast:
                backOfferFunction = BackOfferFunction.create(2, 3000, EqualJitter);
                break;
            default:
                LOGGER.warn("unknown tikv back offer type:{}", type);
                backOfferFunction = BackOfferFunction.create(10, 2000, NoJitter);
                break;
        }
        return backOfferFunction;
    }

    @Override
    public boolean doBackOff(BoType type, Exception err) {
        return doBackOffWithMaxSleep(type, -1, err);
    }

    @Override
    public long nextBackOffTime(BoType type, Exception err) {
        BackOfferFunction backOffFunc = backOffFuncMap.computeIfAbsent(type, this::createBackOffFunc);
        long sleep = backOffFunc.getSleepMs(-1, lastSleep, attempts);
        if (maxSleep > 0 && totalSleep >= maxSleep ||
            deadline > 0 && System.currentTimeMillis() + sleep >= deadline) {
            LOGGER.warn("{} back off timeout, total sleep:{}, attempts:{}, exception:{}",
                type, totalSleep, attempts, err.getMessage());
            return -1;
        }

        // update state
        attempts++;
        lastSleep = sleep;
        totalSleep += sleep;

        return sleep;
    }

    @Override
    public boolean doBackOffWithMaxSleep(BoType type, long maxSleepMs, Exception err) {
        BackOfferFunction backOffFunc = backOffFuncMap.computeIfAbsent(type, this::createBackOffFunc);
        long sleep = backOffFunc.getSleepMs(maxSleepMs, lastSleep, attempts);
        if (deadline > 0 && System.currentTimeMillis() + sleep >= deadline) {
            LOGGER.warn("back offer exceeded deadline:{}", deadline);
            return false;
        }

        // update state
        attempts++;
        lastSleep = sleep;
        totalSleep += sleep;

        try {
            Thread.sleep(sleep);
        } catch (InterruptedException ignored) {
        }

        if (maxSleep > 0 && totalSleep >= maxSleep) {
            LOGGER.warn("back offer timeout, max sleep:{}", maxSleep);
            return false;
        }
        return true;
    }

    @Override
    public void checkTimeout() {
        if (!canRetryAfterSleep(BoCheckTimeout)) {
            throw new TiKVException("retry is exhausted");
        }
    }

    @Override
    public boolean canRetryAfterSleep(BoType type) {
        BackOfferFunction backOffFunc = backOffFuncMap.computeIfAbsent(type, this::createBackOffFunc);
        long sleep = backOffFunc.getSleepMs(-1, lastSleep, attempts);
        return deadline <= 0 || System.currentTimeMillis() + sleep < deadline;
    }

}
